/**
 * @program: PavtFirmware
 * @description:
 * @author: zyc
 * @create: 2018-07-02 09:58
 **/
package com.zjpavt.client.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ProcessUtil {
    private static Executor executor =
        new ScheduledThreadPoolExecutor(2,new DefaultThreadFactory("process"));

    public static void exmple() {
        String mac = null;
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            // linux下的命令，一般取eth0作为本地主网卡
            // 显示信息中包含有mac地址信息
            process = Runtime.getRuntime().exec("ifconfig eth0");
            bufferedReader = new BufferedReader(new InputStreamReader(
                                                    process.getInputStream()));
            String line = null;
            int index = -1;
            while ((line = bufferedReader.readLine()) != null) {
                // 寻找标示字符串[hwaddr]
                index = line.toLowerCase().indexOf("hwaddr");
                // 找到了
                if (index >= 0) {
                    // 取出mac地址并去除2边空格
                    mac = line.substring(index + "hwaddr".length() + 1).trim();
                    break;
                }
            }
        } catch (IOException e) {
            log.debug(LoggerUtil.convertException2String(e));

        }
        finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                log.debug(LoggerUtil.convertException2String(e1));
            }
            bufferedReader = null;
            process = null;
        }
    }


    /**
     * 只需要执行  不考虑是否成功
     *
     * @param shString
     */
    public static void execWithoutReturn(String shString) {
        Process process = null;
        try {
            // linux下的命令，一般取eth0作为本地主网卡
            // 显示信息中包含有mac地址信息
            process = Runtime.getRuntime().exec(shString);
        } catch (IOException e) {
            log.debug(LoggerUtil.convertException2String(e));
        }
        finally {
            process = null;
        }
    }
    /**
     * 执行特定指令并等待
     * @param command
     * @throws IOException
     * @throws InterruptedException
     */
    public static void runCommandWait(String command) throws IOException, InterruptedException {
        Process p = Runtime.getRuntime().exec(command);
        processPrinter(p.getErrorStream());
        processPrinter(p.getInputStream());
        p.waitFor();
    }
    public static void runCommandWait(String command, long time) throws IOException, InterruptedException {
        long startTime = System.currentTimeMillis();
        Process p = Runtime.getRuntime().exec(command);
        processPrinter(p.getErrorStream());
        processPrinter(p.getInputStream());
        p.waitFor(time, TimeUnit.MILLISECONDS);
        log.info("runCommandWait command=" + command + " cost time "+ (System.currentTimeMillis() - startTime));
    }
    /**
     * 执行特定指令不等待
     * @param command
     * @throws IOException
     * @throws InterruptedException
     */
    public static void runCommand(String command) throws IOException, InterruptedException {
        Process p = Runtime.getRuntime().exec(command);
        processPrinter(p.getErrorStream());
        processPrinter(p.getInputStream());
    }
    /**
     * 执行 并返回所有输出内容
     *
     * @return
     */
    public static String exec(String shString) {
        BufferedReader bufferedReader = null;
        Process process;
        try {
            process = Runtime.getRuntime().exec(shString);
            bufferedReader = new BufferedReader(new InputStreamReader(
                                                    process.getInputStream()));
            String line;
            StringBuilder processOutputSb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                processOutputSb.append(line);
            }
            return processOutputSb.toString();
        } catch (IOException e) {
            log.debug(LoggerUtil.convertException2String(e));
            return null;
        }
        finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                log.debug(LoggerUtil.convertException2String(e1));
            }
            bufferedReader = null;
            process = null;
            log.info(shString + " exec FINISHED");
        }
    }
    /**
     * 执行 并返回包含有某字符串的一行如果没有则不返回
     *
     * @return
     */
    public static String exec(String shString, String containStr) {
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(shString);
            bufferedReader = new BufferedReader(new InputStreamReader(
                                                    process.getInputStream()));
            String line = null;
            String lowContainStr = containStr.toLowerCase();
            while ((line = bufferedReader.readLine()) != null) {
                if (line.toLowerCase().contains(lowContainStr)) {
                    return line;
                }
            }
        } catch (IOException e) {
            log.debug(LoggerUtil.convertException2String(e));
            return null;

        }
        finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                log.debug(LoggerUtil.convertException2String(e1));
            }
            bufferedReader = null;
            process = null;
        }
        return null;
    }

    /**
     * 执行打印日志不返回
     *
     * @return
     */
    public static String execWithLog(String shString) {
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(shString);
            bufferedReader = new BufferedReader(new InputStreamReader(
                                                    process.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                log.info(line);
            }
        } catch (IOException e) {
            log.debug(LoggerUtil.convertException2String(e));
            return null;
        }
        finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                log.debug(LoggerUtil.convertException2String(e1));
            }
            bufferedReader = null;
            process = null;
            log.info(shString + " execWithlog FINISHED");
        }
        return null;
    }

    /**
     * 将输入流中的内容输出
     * @param inputStream
     */
    private static void processPrinter(InputStream inputStream) {
        executor.execute(() -> {
            BufferedReader br1 = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line1 = null;
                while ((line1 = br1.readLine()) != null) {
                    if (line1 != null) {
                        log.info(line1);
                    }
                }
            } catch (IOException e) {
                log.error(LoggerUtil.convertException2String(e));
            }
            finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(LoggerUtil.convertException2String(e));
                }
            }
        });
    }
}
